package com.hotel.controller;

import com.hotel.entity.User;
import com.hotel.response.MessageUtils;
import com.hotel.response.RestResponse;
import com.hotel.service.UserService;
import com.hotel.utils.HotelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.ws.Response;

/**
 * @author 夏智力
 * @FileName UserController
 * @date 2021/6/23 9:33
 * @Software: IntelliJ IDEA
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(path = "/user", method = RequestMethod.GET)
    public RestResponse selectById(int userId) {
        User user = userService.selectById(userId);
        return  MessageUtils.success(user);
    }

    @RequestMapping(path = "/user/add", method = RequestMethod.POST)
    public RestResponse insertUser(User user) {
        userService.insertUser(user);
        return MessageUtils.success("注册成功！");
    }

    @RequestMapping(path = "/user/update", method = RequestMethod.POST)
    public RestResponse  updateUser(@RequestBody User user) {

        // 如果密码不为空则将新密码加密后存入数据库
        if(user.getPassword() != null ) {
            User u = userService.selectById(user.getId());
            user.setPassword(HotelUtil.md5(user.getPassword() + u.getSalt()));
        }
        userService.updateUser(user);
        return MessageUtils.success("修改成功");
    }

}
